import { instructAttachmentPreview } from '@/services/api/api-instruct-attachment';
import { selectRecord } from '@/services/api/api-instruct-record';
import { CheckOutlined, CopyOutlined, DownloadOutlined } from '@ant-design/icons';
import { DrawerForm, ProFormInstance } from '@ant-design/pro-form';
import { WaterMark } from '@ant-design/pro-layout';
import { useAccess, useModel } from 'umi';
import {
    Alert,
    Button,
    Descriptions,
    Divider,
    Image,
    message,
    Space,
    Spin,
    Tag,
    Typography,
    Upload,
    UploadFile,
} from 'antd';
import { useEffect, useRef, useState } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import { parse } from '@/utils/historyUtils';
import EditRecord from '../record/EditRecord';
import ReceiptAssign from '../receipt/ReceiptAssign';
import ListReceipt from '../receipt/ListReceipt';

const DetailsRecord: React.FC = () => {
    const { initialState } = useModel('@@initialState');

    const ref = useRef<ProFormInstance>();

    const access = useAccess();

    const [record, setRecordState] = useState<InstructRecordData.ResultDetails>();
    const [previewOpen, setPreviewOpen] = useState(false);
    const [previewData, setPreviewData] = useState<{
        id: string;
        name: string;
        mimeType: string;
        url?: string;
    }>();
    const [previewOnlineUrl, setPreviewOnlineUrl] = useState<string>();
    const [previewLoading, setPreviewLoading] = useState(true);

    const [reload, setReloadState] = useState(false);

    const [instructId, setInstructIdState] = useState('');

    const getWindowSize = () => ({
        innerHeight: window.innerHeight,
        innerWidth: window.innerWidth,
    });
    const [windowSize, setWindowSize] = useState(getWindowSize());
    const handleResize = () => {
        setWindowSize(getWindowSize());
    };
    useEffect(() => {
        // 监听
        window.addEventListener('resize', handleResize);
        // 销毁
        return () => window.removeEventListener('resize', handleResize);
    });

    const iframeRef = useRef(null);

    const handleLoad = () => {
        console.log('加载完成');
        setPreviewLoading(false);
    };
    useEffect(() => {
        const iframe = iframeRef.current;
        iframe?.addEventListener('load', handleLoad);
        return () => {
            iframe?.removeEventListener('load', handleLoad);
        };
    }, [previewOnlineUrl]);

    useEffect(() => {
        const { instructId } = parse(location.search) as { instructId: string };
        setInstructIdState(instructId);
        getSubmitDetails(instructId)
    }, [])

    useEffect(() => {
        window.parent.postMessage({ message: '阅读情况改变' }, '*')
    }, [])

    /**
     * 获取 详情
     * @param key
     */
    const getSubmitDetails = async (id: string) => {
        try {
            const response = await selectRecord({ id: id });
            if (response.code === 0) {
                // document.title = response.data.name;
                setRecordState(response.data);
            }
        } catch (error) { }
    };

    return (


        <PageContainer
            // style={{ paddingInline: '20%' }}
            header={{
                title: (
                    <span>{record?.name}</span>
                ),
                breadcrumb: {
                    items: [],
                },
                style: {
                    paddingBlockEnd: 0,
                },
                extra: (
                    (access.宣传指令x配置x管理员 && record) && <EditRecord
                        key="edit_role"
                        recored={record}
                        onRefurbish={() => {
                            getSubmitDetails(instructId)
                        }}
                    />
                )
            }}
        >
            <Spin spinning={record ? false : true}>
                <WaterMark content={`宣传指令 - ${initialState?.currentUser?.name}`}>
                    <>
                        {record && (
                            <>
                                <div>
                                    <Space
                                        wrap
                                        style={{
                                            marginBottom: 16,
                                        }}
                                    >
                                        {/* {record.run !== 4 && (
                      <Tag
                        color={
                          record.run === 1
                            ? 'green'
                            : record.run === 2
                            ? 'error'
                            : record.run === 3
                            ? 'warning'
                            : 'success'
                        }
                      >
                        {record.run === 1
                          ? '进行中'
                          : record.run === 2
                          ? '已结束 '
                          : record.run === 3
                          ? '暂停'
                          : '已完成'}
                      </Tag>
                    )} */}
                                        <Tag
                                            color={
                                                record.grade === 1 ? '#f50' : record.grade === 2 ? '#ffd591' : '#2db7f5'
                                            }
                                        >
                                            {record.grade === 1 ? '重大' : record.grade === 2 ? '重要' : '一般'}
                                        </Tag>
                                        <Tag color={record.type === 1 ? '#f50' : '#ffd591'}>
                                            {record.type === 1 ? '中宣' : '市宣'}
                                        </Tag>
                                    </Space>
                                </div>

                                {/* {access.宣传指令x配置x管理员 &&
                        record.isHasView === 1 &&
                        record.isView === 0 ? (
                          <Tag color={'#F9CF59'} key="tag_is_has_view">
                            需要阅读
                          </Tag>
                        ) : (
                          <></>
                        )} */}

                                {!access.宣传指令x配置x管理员 && (
                                    <Descriptions>
                                        <Descriptions.Item label="操作情况">
                                            <Space wrap>
                                                <Tag
                                                    color={record.isView === 0 ? '#F9CF59' : '#1AA15F'}
                                                    key="recordExamineType"
                                                >
                                                    {record.isView === 0 ? '未阅读' : '已阅读'}
                                                </Tag>
                                                {record?.isComplete === 1 ? (
                                                    <Tag color={'success'}>{'已完成'}</Tag>
                                                ) : (
                                                    <Tag color={record?.completeType === 1 ? 'success' : 'error'}>
                                                        {record?.completeType === 1 ? '无需回执' : '需要回执'}
                                                    </Tag>
                                                )}
                                            </Space>
                                        </Descriptions.Item>
                                    </Descriptions>
                                )}
                                <Descriptions>
                                    <Descriptions.Item label="创建时间">{record?.createdTime}</Descriptions.Item>
                                    <Descriptions.Item label="截止时间">{record?.deadlineTime}</Descriptions.Item>
                                </Descriptions>
                                <Descriptions>
                                    <Descriptions.Item label="发布单位">
                                        {record?.createdOrganizationName}
                                    </Descriptions.Item>
                                    <Descriptions.Item label="发布人">{record?.createdAccountName}</Descriptions.Item>
                                    <Descriptions.Item label="联系方式">
                                        {record?.createdAccountPhone}
                                    </Descriptions.Item>
                                </Descriptions>
                                {access.宣传指令x配置x管理员 ? (
                                    <Descriptions>
                                        <Descriptions.Item label="指令要求">
                                            <Tag color={record?.completeType === 1 ? 'success' : 'error'}>
                                                {record?.completeType === 1 ? '无需回执' : '需要回执'}
                                            </Tag>
                                        </Descriptions.Item>

                                        <Descriptions.Item label="">
                                            <ReceiptAssign
                                                id={record.id}
                                                receipt={'阅读情况：' + record.read}
                                                type="read"
                                                isRun={record.run === 1}
                                            />
                                        </Descriptions.Item>
                                        <Descriptions.Item label="">
                                            <ReceiptAssign
                                                id={record.id}
                                                receipt={'回执情况：' + record.receipt}
                                                type="receipt"
                                                isRun={record.run === 1}
                                            />
                                        </Descriptions.Item>
                                    </Descriptions>
                                ) : (
                                    <></>
                                )}
                                <Divider />
                                {record?.name ? (
                                    <Typography.Title
                                        copyable={{
                                            icon: [
                                                <CopyOutlined
                                                    style={{
                                                        fontSize: '16px',
                                                    }}
                                                    key="copy-icon"
                                                />,
                                                <CheckOutlined
                                                    style={{
                                                        fontSize: '16px',
                                                    }}
                                                    key="copied-icon"
                                                />,
                                            ],
                                        }}
                                        level={3}
                                        style={{ textAlign: 'center' }}
                                    >
                                        {record?.name}
                                    </Typography.Title>
                                ) : (
                                    <Typography.Title level={3} style={{ textAlign: 'center' }}>
                                        暂无标题
                                    </Typography.Title>
                                )}
                                <Typography.Paragraph
                                    copyable={{
                                        icon: [
                                            <Tag color="#108ee9" key="copy-icon">
                                                复制全文
                                            </Tag>,
                                            <CheckOutlined
                                                style={{
                                                    fontSize: '16px',
                                                }}
                                                key="copied-icon"
                                            />,
                                        ],
                                        text: async () =>
                                            new Promise((resolve) => {
                                                var tempDivElement = document.createElement('div');
                                                tempDivElement.innerHTML = record?.content;
                                                resolve(tempDivElement.textContent || tempDivElement.innerText || '');
                                            }),
                                    }}
                                />

                                <div
                                    dangerouslySetInnerHTML={{
                                        __html: `${record?.content}`,
                                    }}
                                />
                            </>
                        )}
                        {record?.attachments && record?.attachments.length > 0 && (
                            <>
                                <Divider />
                                <div
                                    style={{
                                        textAlign: 'right',
                                    }}
                                >
                                    <Button
                                        type="primary"
                                        key="import"
                                        size="small"
                                        icon={<DownloadOutlined />}
                                        onClick={() => {
                                            record?.attachments.forEach(function (item) {
                                                window.open(item.content, '_blank');
                                            });
                                        }}
                                    >
                                        全部下载
                                    </Button>
                                </div>

                                <Upload
                                    listType="picture"
                                    multiple
                                    fileList={record?.attachments.map((item) => {
                                        return {
                                            uid: item.id,
                                            name: item.name,
                                            url: item.content,
                                            mimeType: item.mimeType,
                                            status: 'done',
                                        };
                                    })}
                                    showUploadList={{
                                        downloadIcon: (
                                            <div style={{ marginLeft: '-100px', padding: '17px 0', marginTop: '-15px' }}>
                                                <DownloadOutlined
                                                    style={{
                                                        marginRight: '10px',
                                                    }}
                                                />
                                                点击下载
                                            </div>
                                        ),
                                        showRemoveIcon: false,
                                        showDownloadIcon: true,
                                    }}
                                    onPreview={async (file: UploadFile) => {
                                        setPreviewData({
                                            id: file.uid,
                                            name: file.name,
                                            mimeType: file.mimeType,
                                            url: file.url,
                                        });
                                        setPreviewOpen(true);
                                    }}
                                />
                                <DrawerForm
                                    title={previewData?.name}
                                    drawerProps={{
                                        width: 900,
                                        destroyOnClose: true,
                                    }}
                                    visible={previewOpen}
                                    onVisibleChange={async (visible) => {
                                        if (visible) {
                                            if (
                                                previewData?.mimeType !== null &&
                                                previewData?.mimeType?.indexOf('image') > -1
                                            ) {
                                                //图片预览
                                            } else {
                                                setPreviewLoading(true);
                                                const response = await instructAttachmentPreview({
                                                    id: previewData?.id,
                                                });

                                                if (response.code === 0) {
                                                    setPreviewOnlineUrl(response.data);
                                                } else {
                                                    message.error('暂时无法预览');
                                                    setPreviewLoading(false);
                                                }
                                            }
                                        } else {
                                            setPreviewOpen(false);
                                            setPreviewData(undefined);
                                            setPreviewOnlineUrl(undefined);
                                        }
                                    }}
                                    submitter={{
                                        searchConfig: {
                                            submitText: '下载',
                                        },
                                    }}
                                    onFinish={async (values) => {
                                        window.open(previewData?.url, '_blank');
                                    }}
                                >
                                    <Alert
                                        style={{
                                            marginBottom: 20,
                                        }}
                                        message="部分文件系统可能暂不支持在线预览，建议下载到本地"
                                        type="warning"
                                        showIcon
                                    />
                                    {previewData?.mimeType !== null &&
                                        previewData?.mimeType?.indexOf('image') > -1 ? (
                                        <Image width="100%" src={previewData?.url} />
                                    ) : (
                                        <Spin spinning={previewLoading}>
                                            <iframe
                                                ref={iframeRef}
                                                src={previewOnlineUrl}
                                                height={windowSize.innerHeight - 220}
                                                width="100%"
                                                frameBorder="0"
                                                // scrolling="false"
                                                allowFullScreen={true}
                                            // scrolling={'no'}
                                            />
                                        </Spin>
                                    )}
                                </DrawerForm>
                            </>
                        )}
                        <Divider
                            style={{
                                marginBottom: -10,
                            }}
                        />
                        {(record && record.completeType === 3) && <ListReceipt recordId={record?.id} type={2} reload={reload} />}
                    </>
                </WaterMark>
            </Spin>
        </PageContainer>
    );
};

export default DetailsRecord;
